package com.uplift.sec.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.filter.OncePerRequestFilter;

import com.uplift.common.Const;
import com.uplift.common.result.IResultable;
import com.uplift.common.result.ResultWrapper4Layui;
import com.uplift.common.utils.URLMatcher;
import com.uplift.common.utils.WebMessage;
import com.uplift.sec.SecurityContext;

/**
 * 安全认证过滤器
 * 
 * @author bcwang
 *
 */
public class SecurityFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		// 检查是否为不受保护的地址
		boolean unprotect = false;
		String url = request.getServletPath();
		for (String unprotectUrl : Const.UNPROTECT_URL) {
			unprotect = URLMatcher.match(unprotectUrl, url);
			if (unprotect) {
				break;
			}
		}
		// 1、不受保护的地址直接放行
		// 2、受保护的地址验证是否登录，如果登录设置SecurityContext，否则JSON响应
		if (unprotect) {
			filterChain.doFilter(request, response);
		} else {
			HttpSession session = request.getSession();
			Object obj = session.getAttribute(Const.SESSION_USER);
			if (obj == null) {
				IResultable result = ResultWrapper4Layui.wrapMap(null, ResultWrapper4Layui.FAIL, "无权访问");
				WebMessage.sendJsonMessageIgnoreEx(response, result);
			} else {
				@SuppressWarnings("unchecked")
				Map<String, Object> user = (Map<String, Object>)obj;
				SecurityContext.setUser(user);
				filterChain.doFilter(request, response);
			}
		}
	}

}
